<?php

require_once(dirname(__FILE__) . '/EventDispatcher.php');

/**
 * Description of SocketServer
 *
 * @author Gvozd
 */
class SocketServer extends EventDispatcher {

    private $clients = array();
    public $socket = NULL;

    public function __construct($ip = '127.0.0.1', $port = 9700) {
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if (!socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
            echo socket_strerror(socket_last_error($this->socket));
            exit;
        }
        socket_bind($this->socket, $ip, $port);
        socket_listen($this->socket);
        socket_set_nonblock($this->socket);
        $timer = Tick::getInstance();
        $timer->addEventListener('tick', array($this, 'Wait'));
    }

    public function __destruct() {
        foreach ($this->clients as $client) {
            socket_close($client);
        }
        if (NULL !== $this->socket) {
            socket_close($this->socket);
        }
    }

    public function Wait(Event $event) {
        //Wait for new connection
        $ready = socket_select($t0 = array($this->socket), $t1 = null, $t2 = null, 0, 100);
        if ($ready) {
            if (($newc = socket_accept($this->socket)) !== false) {
                echo "Client $newc has connected\n";
                //socket_set_nonblock($newc);
                $this->clients[] = $newc;
            }
        }
        //Check every connection
        if (!empty($this->clients)) {
            $r_clients = $this->clients;
            $ready = socket_select($r_clients, $t1 = null, $t2 = null, 0, 100);
            foreach ($r_clients as $client) {
                //тут можно читать каждого клиента
                socket_set_nonblock($client);
                $input = '';
                while ($t = socket_read($client, 4096)) {
                    $input .= $t;
                }
                //$input2 = socket_read($client, 4096);
                //var_dump($input2);
                //echo $input;
                //}
                echo "\n++++++++++++++++++++\n";
                $buffer = "HTTP/1.0 200 OK\n";
                $buffer .= "Server: nginx\n";
                $buffer .= "\n";
                $buffer .= "qwe";

                socket_write($client, $buffer);
                $k = array_search($client, $this->clients);
                unset($this->clients[$k]);
                socket_close($client);
            }
        }
    }

    public function processRequest($request) {
        ; //
    }

}

?>
